package com.honry.identityaccess.infrastructure.persistence;

import java.util.Collection;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.boot.model.source.internal.hbm.HibernateTypeSourceImpl;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.type.StringType;

import com.honry.common.AssertionConcern;
import com.honry.common.port.adapter.persistence.hibernate.AbstractHibernateSession;
import com.honry.identityaccess.domain.model.identity.User;
import com.honry.identityaccess.domain.model.identity.UserRepository;

import aj.org.objectweb.asm.Type;

public class HibernateUserRepository extends AbstractHibernateSession implements UserRepository {

	@Override
	public void add(User user) {
		try {
			this.session().saveOrUpdate(user);
		} catch (ConstraintViolationException e) {
			throw new IllegalStateException("用户已经存在.",e);
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<User> allSimilarlyNamedUsers(String name) {
		Query query=
				this.session().createQuery(
				"from com.honry.identityaccess.domain.model.identity.User as user "
				+ "where user.person.name like ?");
		
		query.setParameter(0,name+"%",new StringType());
		return query.list();
	}

	@Override
	public void remove(User user) {
		this.session().delete(user);
	}

	@Override
	public User userFromAuthenticCredentials(String username, String encryptedPassword) {
		Query query=
				this.session().createQuery(
				"from com.honry.identityaccess.domain.model.identity.User as user "
				+ "where user.username = ? and user.password= ? ");
		
		query.setParameter(0,username,new StringType());
		query.setParameter(1,encryptedPassword,new StringType());
		return (User)query.uniqueResult();
	}

	@Override
	public User userWithUsername(String username) {
		Query query=
				this.session().createQuery(
				"from com.honry.identityaccess.domain.model.identity.User as user "
				+ "where user.username = ? ");
		
		query.setParameter(0,username,new StringType());
		return (User)query.uniqueResult();
	}
}
